package com.sh.shanhuo.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.sh.shanhuo.R;
import com.sh.shanhuo.bean.BaseBean;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.ScreenSwitch;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class WebActivity extends BaseActivity {
    private static final String TAG = WebActivity.class.getSimpleName();
    private TextView titleText;
    private String url;
    private WebView webView;
    private String currentUrl;
    private boolean shouldGoMain;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView() {
        super.initView();
        ImageView back = findViewById(R.id.back);
        titleText = findViewById(R.id.titleText);
        back.setOnClickListener(v -> onBackPressed());
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        if (intent == null)
            return;
        Bundle bundle = intent.getExtras();
        if (bundle == null)
            return;
        url = bundle.getString("url", "https://www.baidu.com/");
        shouldGoMain = bundle.getBoolean("shouldGoMain", false);
        initWebView();
        openSiteStatistics(bundle.getString("id", "0"));
    }

    private void openSiteStatistics(String siteId) {
        Map<String, String> params = new HashMap<>();
        params.put("id", siteId);
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.COUNT_SITE_VIEWS, params, new GsonObjectCallback<BaseBean>() {
            @Override
            public void onUi(BaseBean baseBean) {

            }

            @Override
            public void onFailed(Call call, IOException e) {

            }
        });
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        webView = findViewById(R.id.webContent);
        WebSettings webSettings = webView.getSettings();
        //设置webView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        //webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //关闭webView中缓存

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webView的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        webSettings.setDisplayZoomControls(false);
        //webSettings.setBuiltInZoomControls(true);
        //webSettings.setSupportZoom(true);//设定支持缩放
        webView.setInitialScale(100);
        if (!url.contains("https://") && !url.contains("http://")) {
            url = "https://" + url;
        }
        webView.loadUrl(url);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                WebView.HitTestResult hit = view.getHitTestResult();
                Log.e(TAG, "Type=" + hit.getType() + " Extra=" + hit.getExtra());
                if (TextUtils.equals(currentUrl, url)) {
                    return false;
                } else {
                    currentUrl = url;
                }

                if (url.startsWith("http://") || url.startsWith("https://")) { //加载的url是http/https协议地址
                    view.loadUrl(url);
                } else { //加载的url是自定义协议地址
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                titleText.setText(title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });

        webView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri = Uri.parse(url);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setData(uri);
            startActivity(intent);
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void finish() {
        if (shouldGoMain) {
            ScreenSwitch.startActivity(this, MainActivity.class, null);
        }
        super.finish();
    }
}
